from django.db import models
from django.contrib.auth.models import User
from django.core.validators import RegexValidator
from decimal import Decimal


class UserProfile(models.Model):
    """用户扩展信息"""
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    avatar = models.ImageField(upload_to='avatars/', blank=True, null=True, verbose_name='头像')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '用户资料'
        verbose_name_plural = '用户资料'

    def __str__(self):
        return f"{self.user.username}的资料"


class PhoneNumber(models.Model):
    """手机号码模型"""
    phone_regex = RegexValidator(
        regex=r'^1[3-9]\d{9}$',
        message="手机号码格式不正确，请输入11位有效手机号码"
    )
    
    number = models.CharField(
        max_length=11, 
        validators=[phone_regex], 
        unique=True,
        verbose_name='手机号码'
    )
    user = models.ForeignKey(
        User, 
        on_delete=models.CASCADE, 
        related_name='phone_numbers',
        verbose_name='所属用户'
    )
    is_primary = models.BooleanField(default=False, verbose_name='是否为主号码')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '手机号码'
        verbose_name_plural = '手机号码'
        ordering = ['-is_primary', '-created_at']

    def __str__(self):
        return self.number

    def save(self, *args, **kwargs):
        # 确保每个用户只有一个主号码
        if self.is_primary:
            PhoneNumber.objects.filter(user=self.user, is_primary=True).update(is_primary=False)
        super().save(*args, **kwargs)


class Plan(models.Model):
    """套餐模型"""
    name = models.CharField(max_length=100, verbose_name='套餐名称')
    description = models.TextField(blank=True, verbose_name='套餐描述')
    monthly_fee = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='月费(元)')
    data_allowance = models.IntegerField(verbose_name='流量额度(MB)')
    voice_allowance = models.IntegerField(verbose_name='语音额度(分钟)')
    sms_allowance = models.IntegerField(default=0, verbose_name='短信额度(条)')
    is_active = models.BooleanField(default=True, verbose_name='是否启用')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '套餐'
        verbose_name_plural = '套餐'

    def __str__(self):
        return f"{self.name} - ¥{self.monthly_fee}"


class PhonePlan(models.Model):
    """手机号码套餐关联"""
    phone_number = models.OneToOneField(
        PhoneNumber, 
        on_delete=models.CASCADE, 
        related_name='phone_plan',
        verbose_name='手机号码'
    )
    plan = models.ForeignKey(
        Plan, 
        on_delete=models.CASCADE, 
        related_name='phone_plans',
        verbose_name='套餐'
    )
    start_date = models.DateTimeField(auto_now_add=True, verbose_name='开始时间')
    end_date = models.DateTimeField(blank=True, null=True, verbose_name='结束时间')
    is_active = models.BooleanField(default=True, verbose_name='是否激活')

    class Meta:
        verbose_name = '号码套餐'
        verbose_name_plural = '号码套餐'

    def __str__(self):
        return f"{self.phone_number.number} - {self.plan.name}"


class Balance(models.Model):
    """余额模型"""
    phone_number = models.OneToOneField(
        PhoneNumber, 
        on_delete=models.CASCADE, 
        related_name='balance',
        verbose_name='手机号码'
    )
    amount = models.DecimalField(
        max_digits=10, 
        decimal_places=2, 
        default=Decimal('0.00'),
        verbose_name='余额(元)'
    )
    data_remaining = models.IntegerField(default=0, verbose_name='剩余流量(MB)')
    voice_remaining = models.IntegerField(default=0, verbose_name='剩余语音(分钟)')
    sms_remaining = models.IntegerField(default=0, verbose_name='剩余短信(条)')
    last_updated = models.DateTimeField(auto_now=True, verbose_name='最后更新时间')

    class Meta:
        verbose_name = '余额信息'
        verbose_name_plural = '余额信息'

    def __str__(self):
        return f"{self.phone_number.number} - 余额: ¥{self.amount}"

    def update_allowance(self):
        """更新剩余额度"""
        try:
            phone_plan = self.phone_number.phone_plan
            if phone_plan and phone_plan.is_active:
                self.data_remaining = phone_plan.plan.data_allowance
                self.voice_remaining = phone_plan.plan.voice_allowance
                self.sms_remaining = phone_plan.plan.sms_allowance
                self.save()
        except PhonePlan.DoesNotExist:
            pass


class Payment(models.Model):
    """缴费记录"""
    PAYMENT_METHOD_CHOICES = [
        ('alipay', '支付宝'),
        ('wechat', '微信支付'),
        ('bank', '银行卡'),
        ('cash', '现金'),
    ]

    phone_number = models.ForeignKey(
        PhoneNumber, 
        on_delete=models.CASCADE, 
        related_name='payments',
        verbose_name='手机号码'
    )
    amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='缴费金额(元)')
    payment_method = models.CharField(
        max_length=20, 
        choices=PAYMENT_METHOD_CHOICES, 
        verbose_name='缴费方式'
    )
    payment_time = models.DateTimeField(auto_now_add=True, verbose_name='缴费时间')
    description = models.CharField(max_length=200, blank=True, verbose_name='备注')

    class Meta:
        verbose_name = '缴费记录'
        verbose_name_plural = '缴费记录'
        ordering = ['-payment_time']

    def __str__(self):
        return f"{self.phone_number.number} - ¥{self.amount} - {self.payment_time.strftime('%Y-%m-%d %H:%M')}"

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        # 缴费后更新余额
        balance, created = Balance.objects.get_or_create(phone_number=self.phone_number)
        balance.amount += self.amount
        balance.save()


class UsageRecord(models.Model):
    """使用记录"""
    USAGE_TYPE_CHOICES = [
        ('data', '流量使用'),
        ('voice', '语音使用'),
        ('sms', '短信使用'),
    ]

    phone_number = models.ForeignKey(
        PhoneNumber, 
        on_delete=models.CASCADE, 
        related_name='usage_records',
        verbose_name='手机号码'
    )
    usage_type = models.CharField(max_length=20, choices=USAGE_TYPE_CHOICES, verbose_name='使用类型')
    amount_used = models.IntegerField(verbose_name='使用量')
    usage_time = models.DateTimeField(auto_now_add=True, verbose_name='使用时间')
    description = models.CharField(max_length=200, blank=True, verbose_name='描述')

    class Meta:
        verbose_name = '使用记录'
        verbose_name_plural = '使用记录'
        ordering = ['-usage_time']

    def __str__(self):
        return f"{self.phone_number.number} - {self.get_usage_type_display()} - {self.amount_used}"